import React from 'react';
import style from './style.styl';
import selfStyle from '../self/style.styl';
import {ScrollMenu,ScrollTitle, ScrollBox,AutosaveTextarea,success,error, Button, Modal, Select} from '../../../../ui-components';
import { Avatar, IconButton } from 'sq-ui';
import cx from 'classnames';

import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as reviewAction from '../../../../actions/review.action' 

import SelfProjectItem from '../self/SelfProjectItem';
import OtherContent from './OtherContent';
import ReviewHeader from '../tool/ReviewHeader';
import {buildText} from '../tool/util';
import ReactTooltip from 'react-tooltip';

@connect(({ app, review }) => ({ app, review }), dispatch => ({actions: bindActionCreators({...reviewAction}, dispatch)}))
class PeerIndex extends React.Component {
  static contextTypes = {
    router: React.PropTypes.object
  }
  constructor(props) {
    super(props);
    this.displayName = 'PeerIndex';
    this.state = {
      reviewerState: [],
      refuseInvitationShow: false,
      score: 0,
      cancelDis: false,
    }
  }
  componentDidMount() {
    const {
      itemId
    } = this.props.routeParams;
    this.props.actions.fetchReviewItem(itemId, 'invitations'); 
  }
  componentWillReceiveProps(nextProps) {
    const {
      reviewItem
    } = this.props.review;
    this.setState({
      score: reviewItem.score || 0
    });
  }
  checkChange = () => {
    return !~this.state.reviewerState.findIndex(v => v.item && v.item.isChange);
  }
  setQuestionComment = (questionId, commentId, value) => {
    const {
      reviewItem
    } = this.props.review;

    if(commentId){
      this.props.actions.updateReviewerComment(reviewItem.invitationId, questionId, commentId, {content: value});
    }else
      this.props.actions.addReviewerComment(reviewItem.invitationId, questionId, {content: value});    
  }
  setProjectComment = (questionId, commentId, value) => {
    const {
      reviewItem
    } = this.props.review;

    if(commentId){
      this.props.actions.updateReviewerProjectComment(reviewItem.invitationId, questionId, commentId, {content: value});
    }else
      this.props.actions.addReviewerProjectComment(reviewItem.invitationId, questionId, {content: value});    
  }
  setReviewerState = (questionId, commentId, item, type) => {
    const {
      reviewerState,
    } = this.state;
    const commentItem = reviewerState.filter(v => v.questionId === questionId);
    if(commentItem.length){
      this.setState({
        reviewerState: reviewerState.map(v => {
          if(v.questionId === questionId){
            return {
              ...v,
              commentId,
              item,
              type,
            }
          }else{
            return v;
          }
        })
      });
    }else{
      this.setState({
        reviewerState: [
          ...reviewerState,
          {
            questionId,
            commentId,
            item,
            type,
          }
        ]
      });
    }
  }
  saveAll = () => {
    const {
      reviewerState,
    } = this.state;
    reviewerState.map(v => {
      if(v.item && v.item.isChange){
        this.refs[`peer-${v.questionId}`].props.onSave(v.item.value);
      }
    });
  }
  onSubmit = () => {
    const {
      reviewItem,
      reviewItemProjects
    } = this.props.review;
    const {
      questions = [],
      isManager,
    } = reviewItem;
    const cb = () => {
      this.context.router.push(`/review/index/${(reviewItem.reviewTemplate||{}).templateId}`);
      success('更新成功!')
    }
    const {
      itemId
    } = this.props.routeParams;
    
    if(!this.checkChange()) {
      this.state.reviewerState.map(v => {
        if(!v.item.value){
          return error('填写项不可为空');
        }
        if(v.item && v.item.isChange)
          this.refs[`peer-${v.questionId}`].props.onSave(v.item.value);
        if(this.checkChange()) {
          //this.props.tabRouter(3);
          if(!this.state.score && isManager){
            return error('请填写主管评分');
          }
          this.props.actions.submitPeerReview(itemId,'invitations',{score: this.state.score}, cb);
        }
      });
    }else{
      if(~[...reviewItemProjects||[], ...questions||[]].findIndex(v => (!v.reviewerComment || !v.reviewerComment.content) 
        && !~this.state.reviewerState.findIndex(k => k.questionId === v.questionId || k.questionId === v.projectId ))){
        return error('填写项不可为空');
      }
      if(!this.state.score && isManager){
        return error('请填写主管评分');
      }
      this.props.actions.submitPeerReview(itemId,'invitations',{score: this.state.score}, cb);
      //this.props.tabRouter(3);
    }
  }
  onCancel = (invitationId) => {
    this.setState({
      cancelDis: true,
    });
    this.props.actions.cancelInvitation({invitationId}, {
      failed: () => {
        this.setState({
          cancelDis: false,
        });
      },
      success: (data) => {
        const {
          itemId
        } = this.props.routeParams;
        this.props.actions.fetchReviewItem(itemId, 'invitations'); 
      }
    });
  }
  onRefuse = () => {
    this.setState({
      refuseInvitationShow: true,
    });
  }
  refuseInvitation = (invitationId) => {
    const {reviewItem={}} = this.props.review;
    const {templateId} = reviewItem.reviewTemplate;
    this.setState({
      refuseInvitationShow: false
    })
    this.props.actions.refuseInvitation(invitationId, ()=> {
      this.context.router.push(`/review/index/${templateId}`);
      success('删除邀请成功!')
    })
  }
  goBack = () => {
    const {
      reviewItem,
    } = this.props.review;
    this.context.router.push(`/review/index/${(reviewItem.reviewTemplate||{}).templateId}`);
  }
  render() {
    const {
      reviewItem,
      reviewItemProjects,
    } = this.props.review;
    const {
      invitationDisplayType,
      projects = [],
      questions = [],
      revieweeUserProfile,
      invitationId,
      isManager,
      reviewTemplate = {},
    } = reviewItem;
    const {
      isReviewerAnonymous
    } = reviewTemplate;
    const flag = this.checkChange();
    const isEditabled = ~[2, 5].indexOf(invitationDisplayType);
    const isSubmit = !isEditabled;
    const isDetail = ~[4].indexOf(invitationDisplayType);
    return (
      <div>
        <ReviewHeader title={reviewItem.revieweeUserProfile ? `给${reviewItem.revieweeUserProfile.fullName}的反馈` : ''} goBack={this.goBack}  />
        {
          isReviewerAnonymous ? 
          <div className={style['info']}>{`本活动为匿名活动，只有HR才能看到反馈文字所对应的姓名，其他人无法获知。${isManager ? '(仅主管有评分权限，因此主管评分无法匿名)': ''}`}</div>
          : null
        }
        <ScrollMenu>
          {
            !reviewItemProjects.length ? null : <ScrollTitle title={'按项目反馈'} name={'ScrollTitle'}/>
          }
          {
            reviewItemProjects.map((v, i) => {
              return (
                <ScrollBox key={`q_${i}`} title={v.name}>
                  <div className={style['peer-box']} style={{paddingTop: '1px'}}>
                    <SelfProjectItem  id={invitationId} index={i} viewMode={'invitations'}  item={v} user={revieweeUserProfile} actions={this.props.actions}  isManager={isManager} disabled/>
                    <div className={style['peer-textarea']}>
                      <div className={style['peer-title']}>我的反馈</div>
                      {
                        !isEditabled ? 
                        <div className={selfStyle['question-text']}>
                          {buildText((v.reviewerComment || {}).content)}
                        </div> :
                        <AutosaveTextarea value={(v.reviewerComment || {}).content} 
                          ref={`peer-${v.projectId}`}
                          onSave={(value) => {this.setProjectComment(v.projectId,(v.reviewerComment || {}).commentId, value)}} 
                          onChange={(item) => {this.setReviewerState(v.projectId,(v.reviewerComment || {}).commentId, item, 'project')}} 
                        />
                      }
                    </div>
                  </div> 
                </ScrollBox>
              );
            })
          }
          {
            !questions.length ? null : <ScrollTitle title={'通用问题'} name={'ScrollTitle'}/>
          }
          {
            questions.map((v, i) => {
              return (
                <ScrollBox key={`q_${i}`} title={v.name}>
                  <div className={style['peer-box']}>
                    <div  >
                      <div className={selfStyle['question-box']} style={{paddingBottom: 0}}>
                        <div className={selfStyle['question-title']}>{v.name}</div>
                        <div className={selfStyle['avatar-box']}>
                          <Avatar
                            style={{ margin: '0 10px 0 0' }}
                            width={30}
                            src={revieweeUserProfile.avatarUrl}
                          />
                          <div className={selfStyle['avatar-name']}>
                            {revieweeUserProfile.fullName}的自评
                          </div>
                        </div>
                        <div className={selfStyle['question-text']}>
                          {buildText(v.revieweeComment.content)}
                        </div>
                      </div>
                    </div>
                    {
                      isManager ?
                      <OtherContent list={v.submittedComment||[]} />
                      : null
                    }
                    <div className={style['peer-textarea']}>
                      <div className={style['peer-title']}>我的反馈</div>
                      {
                        !isEditabled ? 
                        <div className={selfStyle['question-text']}>
                          {buildText((v.reviewerComment || {}).content)}
                        </div> :
                        <AutosaveTextarea value={(v.reviewerComment || {}).content} 
                          ref={`peer-${v.questionId}`}
                          onSave={(value) => {this.setQuestionComment(v.questionId,(v.reviewerComment || {}).commentId, value)}} 
                          onChange={(item) => {this.setReviewerState(v.questionId,(v.reviewerComment || {}).commentId, item, 'question')}} 
                        />
                      }
                    </div>
                  </div>
                </ScrollBox>
              );
            })
          }
        </ScrollMenu>
        {
          isManager ?
          <div className={style['peer-box']} style={{width: '850px'}}>
            <div className={style['peer-score']}>
              <label>主管评分</label>
              {
                isSubmit ? 
                <p >{`${(reviewItem.score||0)/100 || '尚未评'}分`}
                  <div data-tip data-for='global' className={style['tooltip']}> ?
                    <ReactTooltip id='global' aria-haspopup='true' role='example'>
                     <p>5分 - 表现优异,远超预期</p>
                     <p>4分 - 表现初测,超出预期</p>
                     <p>3分 - 表现很好,符合预期</p>
                     <p>2分 -表现低于预期</p>
                     <p>1分 -不合格</p>
                    </ReactTooltip>
                  </div>
                </p>
                :
                <Select 
                  value={this.state.score} 
                  onChange={e => this.setState({ score: +e.target.value })}
                >
                  <option value="0">请选择..</option>
                  <option value="500">5.00分 - 表现优异,远超预期</option>
                  <option value="475">4.75分</option>
                  <option value="450">4.50分</option>
                  <option value="425">4.25分</option>
                  <option value="400">4.00分 - 表现初测,超出预期</option>
                  <option value="375">3.75分</option>
                  <option value="350">3.50分</option>
                  <option value="325">3.25分</option>
                  <option value="300">3.00分 - 表现很好,符合预期</option>
                  <option value="275">2.75分</option>
                  <option value="250">2.50分</option>
                  <option value="225">2.25分</option>
                  <option value="200">2.00分 - 表现低于预期 </option>
                  <option value="175">1.75分</option>
                  <option value="150">1.50分</option>
                  <option value="125">1.25分</option>
                  <option value="100">1.00分 - 不合格 </option>
                </Select>
              }
              
            </div>
          </div>
          : null
        }
        {
          isDetail ? null :
          isSubmit ?
          <div style={{width: '850px'}}>
            <div className={selfStyle['btn-bar']}>
              <Button label={'撤回并修改'} disabled={this.state.cancelDis} className={selfStyle['r-btn']} onClick={this.onCancel.bind(this,invitationId)} />
              <div className={selfStyle['r-info']}>*反馈已提交</div>
            </div>
          </div>
          :
          <div style={{height: '80px'}}>
            <div className={style['btn-bar']}>
              <div style={{width: '1100px', margin: '0 auto'}}>
                <div style={{width: '850px'}}>
                  <div className={selfStyle['btn-bar']}>
                    {isManager ? null :
                      <Button label={'拒绝反馈'} className={selfStyle['d-btn']} onClick={this.onRefuse} />
                    }
                    <Button label={'提交反馈'} className={selfStyle['r-btn']} onClick={this.onSubmit} />
                    <Button label={'保存草稿'} className={cx({
                      [selfStyle['r-btn']]: true,
                      [selfStyle['bl-dis']]: flag,
                    })} blueLine onClick={() => {!flag && this.saveAll()}} />
                  </div>
                </div>
              </div>
            </div>
          </div>
        }
        <Modal
          onRequestClose={() => this.setState({ refuseInvitationShow: false })}
          active={this.state.refuseInvitationShow}
          actions={[
            'cancel',
            this.refuseInvitation.bind(this, invitationId)
          ]}
          title="拒绝邀请"
        >
          <div>确定拒绝对方的反馈邀请？</div>
        </Modal>
      </div>
    );
  }
}

export default PeerIndex;
